from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.db.models import F
from django.http import JsonResponse
from app01 import models
import json
import os
import random

#我的-个人信息
def infomation(request):
    return render(request, 'info.html')

# 【主页】moment.html
def moment(request):
    u_name = request.session.get('info')['name']
    u_id = models.User.objects.filter(u_name=u_name).first().id
    if request.method == 'GET':
        topics = models.Topic.objects.filter().order_by('-create_time')#获取帖子表
        user = models.User.objects.filter(u_name=u_name).first()
        response = {
            'topics': topics,
            'user': user,
        }
        return render(request, 'moments.html', response)

    elif request.method == 'POST':
        chlst = ['日常','分享心情','晒车','知识贴','我和车']
        t_uid = u_id
        t_content = request.POST.get('t_content')
        t_photo = request.POST.get('t_photo')
        t_uname = models.User.objects.filter(id=u_id).first().u_name
        t_ucha = models.User.objects.filter(id=u_id).first().u_cha
        t_uphoto = models.User.objects.filter(id=u_id).first().u_photo

        n = random.randint(0,4)

        obj = models.Topic.objects.create(t_uid=t_uid, t_uname=t_uname, t_ucha=t_ucha, t_uphoto=t_uphoto, t_content=t_content, t_like=0, t_comment=0, t_share=0, t_chaohua=chlst[n])
        tid = str(obj.id)
        #动态图片的保存
        t_photo_path = ''
        if t_photo:
            # 保存文件
            t_photo_path = 'static/app01/img/t_photo/' + tid + '_' + t_photo.name
            f = open(os.path.join(t_photo_path), 'wb')
            for line in t_photo.chunks():
                f.write(line)
            f.close()
            # 把图片路径存入数据库
            models.Topic.objects.filter(id=tid).update(t_photo='/' + t_photo_path)
            print('photo yeap!')
        return redirect('/moment/')

#【点赞】功能实现
def digg(request):
    print('digg')
    article_id = int(request.POST.get("article_id"))  # 应该传布尔值，反序列化下，而不是字符串
    print('article_id:',article_id)
    # 点赞人即当前登录人
    u_name = request.session.get('info')['name']
    user_id = models.User.objects.filter(u_name=u_name).first().id
    tp = models.Topic.objects.filter(id = article_id)
    tp.update(t_like=F("t_like")+1)
    response = {"state": True}
    return JsonResponse(response)

#【我的动态】mymmt.html
def mymmt(request):
    u_name = request.session.get('info')['name']
    if request.method == 'GET':
        user = models.User.objects.filter(u_name=u_name).first()
        u_id = models.User.objects.filter(u_name=u_name).first().id
        topics = models.Topic.objects.filter(t_uid=u_id).order_by('-create_time')#获取帖子表

        response = {
            'topics': topics,
            'uid': u_id,
            'user': user,
        }
        return render(request, 'profile.html', response)

    elif request.method == 'POST':
        # 删除动态
        p_type = request.POST.get('type')
        if p_type == 'delete':
            response = {'msg': '', 'status': False}
            tid = request.POST.get('t_id')
            models.Topic.objects.filter(id=tid).delete()
            response['status'] = True
            return HttpResponse(json.dumps(response))
        if not u_name:
            return redirect('/signin/')

        return redirect('/mymmt/')

# 【动态详情】mmtdetail.html
def detail(request, tid):
    if request.method == 'GET':
        # 帖子内容
        # 时间类别作者，标题，正文，图片path
        try:
            topic = models.Topic.objects.get(id=tid)
        except Exception as e:
            return redirect('/moment/')

        t_uid = topic.t_uid
        t_uname = topic.t_uname
        t_ucha = topic.t_ucha
        t_uphoto = topic.t_uphoto

        t_time = topic.create_time
        t_content = topic.t_content
        t_photo = topic.t_photo

        t_like = topic.t_like
        t_comment = topic.t_comment
        t_share = topic.t_share
        u_name = request.session.get('info')['name']

        response = {
            #'uid': uid,
            't_uid': t_uid,
            't_uname':t_uname,
            't_ucha':t_ucha,
            't_uphoto':t_uphoto,

            'tid': tid,
            't_time': t_time,
            't_content': t_content,
            't_photo': t_photo,
            't_like': t_like,
            't_comment': t_comment,
            't_share': t_share,
        }

        # 留言内容
        # 留言者，留言时间，留言内容
        replys = models.Reply.objects.filter(r_tid=tid)
        reply_list = []
        for reply in replys:
            single_reply = {
                'r_uid': reply.r_uid,
                'r_time': reply.r_time,
                'r_content': reply.r_content,
                'id': reply.id,
                'r_photo': reply.r_photo,
                'r_uname': reply.r_uname,
            }
            reply_list.append(single_reply)
        response['reply_list'] = reply_list
        return render(request, 'mmtdetail.html', response)

    elif request.method == 'POST':
        uname = request.session.get('info')['name']
        # 删除回复
        p_type = request.POST.get('type')
        if p_type == 'delete':
            print('yes')
            response = {'msg': '', 'status': False}
            r_id = request.POST.get('id')
            models.Reply.objects.filter(id=r_id).delete()
            response['status'] = True
            return HttpResponse(json.dumps(response))
        if not uname:
            return redirect('/signin')

        # 将回复提交数据库
        r_content = request.POST.get('r_content')
        uid = models.User.objects.filter(u_name=uname).first().id
        obj = models.Reply.objects.create(r_tid=tid, r_uid=uid, r_uname=uname, r_content=r_content)

        r_id = str(obj.id)
        r_photo = request.FILES.get('r_photo')
        r_photo_path = ''
        if r_photo:
            # 保存文件
            r_photo_path = '/static/app01/img/r_photo/' + r_id + '_' + r_photo.name
            f = open(os.path.join(r_photo_path), 'wb+')
            for line in r_photo.chunks():
                f.write(line)
            f.close()
            # 把图片路径存入数据库
            models.Reply.objects.filter(id=r_id).update(r_photo='/'+r_photo_path)

        return redirect('/detail/' + str(tid))

# 【关注列表】myfollow.html
def myfollow(request):
    u_id = request.session.get('info')['id']
    if request.method == 'GET':
        follows = models.Follow.objects.filter(uid=u_id)
        user = models.User.objects.filter(id=u_id).first()
        response = {
            'follows':follows,
            'user': user,
        }
        return render(request, 'myfollow.html', response)

# 【粉丝列表】myfans.html
def myfans(request):
    u_name = request.session.get('info')['name']
    u_id = models.User.objects.filter(u_name=u_name).first().id
    if request.method == 'GET':
        fans = models.Fans.objects.filter(uid=u_id)
        user = models.User.objects.filter(id=u_id).first()
        response = {
            'fans': fans,
            'user': user,
        }
        return render(request, 'myfans.html', response)